$(()=>{



    /******************************************/
    let classGroupID = 0;
    let aInput = null;

    initPage();
    function initPage() {
        // 列出所有用户分组
        let Pr_classGroup = new Promise( (resolve,reject)=>{
            $.ajax({
                url: '/manage/group/list.do',
                type : 'post',
                data : {},
                xhrFields : {
                    withCredentials: true
                },
                crossDomain: true,
                success : function ( data ) {
                    if( data.status === 0 ){
                        resolve(data.data);
                    }else{
                        reject(data);
                    }
                }
            })
        });
        // 列出所有权限
        let Pr_powerList = new Promise( (resolve,reject)=>{
            $.ajax({
                url: '/manage/privilege/list_all.do',
                type : 'post',
                data : {},
                xhrFields : {
                    withCredentials: true
                },
                crossDomain: true,
                success : function ( data ) {
                    if( data.status === 0 ){
                        resolve(data.data);
                    }else{
                        reject(data);
                    }
                }
            })
        });

        let Pr_initPage = Promise.all( [Pr_classGroup,Pr_powerList] );
        Pr_initPage.then( (data)=>{
            To_classGroup( data[0], autoClick );
            To_powerGroup( data[1] );
        } ).catch( (data)=>{
            if( data.status === 10 ){
                spop_waring( data.msg,()=>{},outLogin );
            }else{
                spop_er( data.msg );
            }
        } );
    }

    // 权限分组
    $('.classGroup').on('click','.list-group-item',function (e) {
        let that = $(this);
        $.ajax({
            url : '/manage/privilege/list.do',
            type : 'post',
            data : {
                groupno : that.attr('data-id')
            },
            xhrFields : {
                withCredentials: true
            },
            crossDomain: true,
            success : function (data) {
                console.log(data);
                if(data.status === 0){
                    classGroupID = that.attr('data-id');
                    To_power( data.data, classGroupID);
                    activeCSS(that);
                }else if( data.status === 10 ){
                    spop_waring(data.msg,()=>{},outLogin);
                }else {
                    spop_er(data.msg);
                }
            }
        })
    });

    // 添加权限
    $('#powerForm').on('click','input[type="checkbox"]',function () {
        let that = $(this);
        let thisID = that.val();

        that.prop('disabled', 'disabled');
        if( that.is(':checked') ){
            addPower( classGroupID, thisID, that );
        }else{
            removePower( classGroupID, thisID, that );
        }
    });

    // 添加分组
    $('#addPower-model').on('show.bs.modal',function () {
        $('#newGroupName').val('');
    });
    $('#addGroup-btn').on('click',function(){
        let name = $('#newGroupName').val().trim();
        if( name ){
            addGroup( name );
        }else{
            spop_waring('输入不能未空');
        }
    });

    // 修改分组
    $('#reviseGroup-model').on('show.bs.modal',function (e) {
        let DOM = $(e.relatedTarget).parents('li');
        let name = DOM.find('span').html();
        classGroupID = DOM.attr('data-id');
        $('#reviseGroup-model').find('.form-control-static').text(name);
    });
    $('#reviseGroup-btn').on('click',function () {
        let newName = $('#newReviseGroupName').val().trim();
        if( newName ){
            reviseGroup( newName, classGroupID )
        }
    });

    // 删除分组
    $('#classGoup-UL').on('click','.glyphicon-trash',function () {
        let DOM = $(this).parents('li');
        let groupName = DOM.find('span').html();
        classGroupID = DOM.attr('data-id');


        if(confirm('确定删除<<'+ groupName +'>>权限分组？')){
            delGroup( classGroupID );
        }
    });

    // // 添加单个用户分组
    // $('#addUserGroup').on('show.bs.modal',function () {
    //     let Pr_userList = new Promise( (resolve, reject)=>{
    //         $.ajax({
    //             url: '/manage/user/search_user.do',
    //             type: 'post',
    //             data: {
    //                 pageNum: 0,
    //                 pageSize: 1000,
    //                 name: ''
    //             },
    //             contentType: 'application/x-www-form-urlencoded',
    //             xhrFields: {
    //                 withCredentials: true
    //             },
    //             crossDomain: true,
    //             success: function (data) {
    //                 if (data.status == 0) {
    //                     resolve(data);
    //                     return false;
    //                 } else {
    //                     reject(data);
    //                     return false;
    //                 }
    //             }
    //         });
    //     });
    //     Pr_userList.then( (data)=>{
    //
    //     } ).catch( (data)=>{
    //         if( data.status == 10 ){
    //             spop_waring(data.msg,()=>{},outLogin);
    //         }else{
    //             spop_er(data.msg);
    //         }
    //     } )
    // });

    // 添加权限
    function addPower( groupID, powerID, DOM ) {
        // if( groupID !== 1 || groupID !== 3 ){
            $.ajax({
                url : '/manage/privilege/add_and.do',
                type : 'post',
                data : {
                    permno : powerID,
                    groupno : groupID
                },
                xhrFields : {
                    withCredentials: true
                },
                crossDomain: true,
                success : function (data) {
                    if(data.status === 0){
                        DOM.prop('disabled',false);
                        DOM.parents('label').css('color','#8E1614');
                    }else if( data.status === 10 ){
                        spop_waring(data.msg,()=>{},outLogin);
                    }else {
                        spop_er(data.msg);
                    }
                }
            })
        // }else{
        //     spop_waring('无法修改');
        // }
    }
    // 清除权限
    function removePower( groupID, powerID, DOM ) {

        // if( groupID !== 1 || groupID !== 3 ) {
            $.ajax({
                url: '/manage/privilege/delete_and.do',
                type: 'post',
                data: {
                    groupno: groupID,
                    permno: powerID
                },
                xhrFields: {
                    withCredentials: true
                },
                crossDomain: true,
                success: function (data) {
                    if (data.status === 0) {
                        DOM.prop('disabled', false);
                        DOM.parents('label').css('color', '#333333');
                    } else if (data.status === 10) {
                        spop_waring(data.msg, () => {
                        }, outLogin);
                    } else {
                        spop_er(data.msg);
                    }
                }
            })
        // }else{
        //     spop_waring('无法修改');
        // }
    }
    // 渲染权限
    function To_power(arrPower, status) {
        switch (Number(status)){
            case 1 : allNoChecked( Number(status) );
                break;
            case 3 : allOkChecked( Number(status) );
                break;
            default : offChecked( arrPower, Number(status));
                break;
        }

        function allNoChecked( status ) {
            $(aInput).each((idx,item)=>{
                $(item).prop('checked',false);
                $(item).parents('label').css('color','#333333');
            });
            if( Number(status) === 1 ){
                $(aInput).each((idx,item)=>{
                    $(item).attr('disabled','disabled');
                });
            }
        }
        function offChecked(arrPower,status) {
            allNoChecked();
            for(let i=0; i<arrPower.length; i++){
                for(let j=0; j<aInput.length; j++){
                    if( arrPower[i] === Number($(aInput[j]).val()) ){
                        $(aInput[j]).prop('checked','checked');
                        $(aInput[j]).parents('label').css('color','#8E1614');
                        continue ;
                    }
                }
            }
            if( Number(status) !== 1 || Number(status) !== 3 ){
                $(aInput).each((idx,item)=>{
                    $(item).attr('disabled',false);
                });
            }
        }
        function allOkChecked( status ) {
            $(aInput).each((idx,item)=>{
                $(item).prop('checked','checked');
                $(item).parents('label').css('color','#8E1614');
            });
            if( Number(status) === 3 ){
                $(aInput).each((idx,item)=>{
                    $(item).attr('disabled','disabled');
                });
            }
        }
    }

    // 添加分组组
    function addGroup(name) {
        $.ajax({
            url : '/manage/group/add.do',
            type : 'post',
            data : {
                groupname : name
            },
            xhrFields : {
                withCredentials: true
            },
            crossDomain: true,
            success : function (data) {
                if(data.status === 0){
                    spop_ok( data.msg, function () {
                        getUserGroup();
                        $('#addPower-model').modal('hide');
                    } );
                }else if( data.status === 10 ){
                    spop_waring(data.msg,()=>{},outLogin);
                }else {
                    spop_er(data.msg);
                }
            }
        })
    }
    // 修改分组名
    function reviseGroup(newName,classGroupID) {
        $.ajax({
            url : '/manage/group/update.do',
            type : 'post',
            data : {
                groupname : newName,
                groupno : classGroupID
            },
            xhrFields : {
                withCredentials: true
            },
            crossDomain: true,
            success : function (data) {
                console.log(data);
                if(data.status === 0){
                    spop_ok(data.msg,()=>{
                        getUserGroup( autoClick );
                        $('#reviseGroup-model').modal('hide');
                    })
                }else if( data.status === 10 ){
                    spop_waring(data.msg,()=>{},outLogin);
                }else {
                    spop_er(data.msg);
                }
            }
        })
    }
    // 删除分组
    function delGroup( classGroupID ) {
        $.ajax({
            url: '/manage/group/delete.do',
            type : 'post',
            data : {
                groupno : classGroupID
            },
            xhrFields : {
                withCredentials: true
            },
            crossDomain: true,
            success : function ( data ) {
                if( data.status === 0 ){
                    spop_ok(data.msg, function () {
                        getUserGroup(autoClick);
                    } );
                }else if(data.status == 10){
                    spop_waring(data.msg,()=>{},outLogin);
                }else{
                    spop_ok(data.msg);
                }
            }
        })
    }
    // 获取权限分组
    function getUserGroup( endFn ) {
        $.ajax({
            url: '/manage/group/list.do',
            type : 'post',
            data : {},
            xhrFields : {
                withCredentials: true
            },
            crossDomain: true,
            success : function ( data ) {
                console.log(data);
                if( data.status === 0 ){
                    To_classGroup(data.data, endFn );
                }else if(data.status == 10){
                    spop_waring(data.msg,()=>{},outLogin);
                }else{
                    spop_ok(data.msg);
                }
            }
        })
    }

    // 分组选中CSS
    function activeCSS(DOM) {
        let aDOM = DOM.siblings();
        aDOM.each((idx,item)=>{
            $(item).removeClass('active');
        });
        DOM.addClass('active');
    }

    // 用户分组
    function To_classGroup( data, endFn ){
        let classGroup_Ul = $('.classGroup').find('.list-group');
        classGroup_Ul.html('');
        $(data).each((idx,item)=>{
            let DOM = $('<li class="list-group-item" data-id="'+ item.groupno +'">' +
                '<span>'+ item.groupname +'</span>'+
                '           <div class="Po-a">' +
                '               <i class="glyphicon glyphicon-pencil"  data-toggle="modal" data-target="#reviseGroup-model"></i>' +
                '               <i class="glyphicon glyphicon-trash"></i>' +
                '           </div>' +
                '       </li>');

            if( item.groupno === 1 || item.groupno === 3 ){
                DOM.attr('data-toggle','tooltip').attr('data-placement','right').attr('title','该分组无法修改权限');
            }

            classGroup_Ul.append( DOM );
        });
        $('[data-toggle="tooltip"]').tooltip();
        if( typeof endFn === 'function'){
            endFn();
        }
    }

    // 权限
    function To_powerGroup( data ) {
        let powerForm = $('#powerForm');
        powerForm.html('');
        $(data).each((idx,item)=>{
            let DOM = $('<label class="checkbox-inline">' +
                '            <input type="checkbox" value="'+ item.permno +'">'+ item.permname +
                '         </label>');
            powerForm.append(DOM);
        });
        aInput = powerForm.find('input[type="checkbox"]');
    }

    // 默认选中
    function autoClick() {
        $('.classGroup').find('.list-group-item').eq(0).click();
    }


});